package com.webull.information.center.carwler.dao;

import java.util.Date;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.webull.framework.util.UtilJdbc;
import com.webull.information.center.carwler.common.model.RtrsNewsCollect;
import com.webull.information.center.dao.JdbcHelper;

@Repository
public class RtrsNewsCollectDao {

	private static final Logger logger = LogManager.getLogger(RtrsNewsCollectDao.class);

	private @Autowired JdbcTemplate jdbcTemplate;
	private @Autowired NamedParameterJdbcTemplate npJdbcTemplate;

	private static final RowMapper<RtrsNewsCollect> rtrsCollect = BeanPropertyRowMapper
			.newInstance(RtrsNewsCollect.class);

	/**
	 * 查询&新建
	 * 
	 * @param regionId
	 * @return
	 */
	public RtrsNewsCollect queryCollect(Integer regionId) {
		RtrsNewsCollect newsCollect = UtilJdbc.queryForObject(jdbcTemplate, Sql.getByRegId, rtrsCollect, regionId);
		if (newsCollect == null) {
			newsCollect = new RtrsNewsCollect();
			newsCollect.setRegionId(regionId);
			newsCollect.setExecTime(DateUtils.addDays(new Date(), -2));
			newsCollect.setExecCount(0);
			int id_ = UtilJdbc.insertAndReturnIntKey(npJdbcTemplate, Sql.insert, newsCollect);
			newsCollect.setId(id_);
		}
		return newsCollect;
	}

	public int update(RtrsNewsCollect collect) {
		return npJdbcTemplate.update(Sql.update, JdbcHelper.getSqlParameterSource(collect));
	}

	public int completeReverse(Integer collectId) {
		return jdbcTemplate.update(Sql.update2, collectId);
	}

	private static class Sql {
		private static final String getByRegId = "select * from wli_rtrs_news_collect where del = 0 and region_id = ?";
		private static final String insert = "insert into wli_rtrs_news_collect (region_id,exec_time,exec_count) values (:regionId,:execTime,:execCount)";

		private static final String update = "update wli_rtrs_news_collect SET old_exec_time = ifnull(:oldExecTime,old_exec_time),exec_count = (exec_count + ifnull(:execCount,0)),exec_stat = ifnull(:execStat,exec_stat),exec_time = ifnull(:execTime,exec_time)  where id = :id";

		private static final String update2 = "update wli_rtrs_news_collect SET old_exec_time = null  where id = ?";

	}
}

